package com.cn.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cn.domain.User;
import com.cn.service.UserService;
import com.cn.service.impl.UserServiceImpl;
import com.cn.utils.UserUtils;
import com.sun.org.apache.commons.beanutils.BeanUtils;

public class RegistServlet extends BaseServlet {
	//private UserService us = new UserServiceImpl();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try{
		User user = new User();
		try {
			BeanUtils.populate(user, request.getParameterMap());
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Map<String,String> errors = UserUtils.checkUser(user);
		if(errors.size()>0){
			request.setAttribute("errors", errors);
			request.getRequestDispatcher("/register.jsp").forward(request, response);
			return;
		}
		String code = (String) request.getSession().getAttribute("code");
		System.out.println(code);
		String code1 = request.getParameter("code");
		System.out.println(code1);
		if(code1!=null&&code1.equalsIgnoreCase(code)){
			System.out.println("验证码正确");
			//response.getWriter().write("success");
		}else{
			request.setAttribute("validateError", "验证码错误");
			request.getRequestDispatcher("/register.jsp").forward(request, response);
			return;
		}
		us.register(user);
		response.sendRedirect("/day1302/login.jsp");
	  }catch(Exception e){
		  e.getStackTrace();
		  request.setAttribute("error", e.getMessage());
		  request.getRequestDispatcher("/register.jsp").forward(request, response);
	  }
	}

}
